package com.dd.shop4j.console.goods.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.dd.shop4j.common.utils.ImageUtils;
import com.dd.shop4j.common.utils.ImageUtils.ImageInfo;
import com.dd.shop4j.common.utils.Page;
import com.dd.shop4j.common.utils.security.ShiroUtils;
import com.dd.shop4j.console.goods.controller.forms.GoodForm;
import com.dd.shop4j.console.goods.controller.forms.GoodsQueryForm;
import com.dd.shop4j.goods.enums.GoodStatus;
import com.dd.shop4j.goods.mapper.GoodsDescriptionMapper;
import com.dd.shop4j.goods.mapper.GoodsImageMapper;
import com.dd.shop4j.goods.mapper.GoodsInfoAttrDetailMapper;
import com.dd.shop4j.goods.mapper.GoodsInfoMapper;
import com.dd.shop4j.goods.model.GoodsDescription;
import com.dd.shop4j.goods.model.GoodsImage;
import com.dd.shop4j.goods.model.GoodsInfo;
import com.dd.shop4j.goods.model.GoodsInfoAttrDetail;

/**
 * 商品信息业务类  <br />
 * <ul style="list-style: decimal;">
 * 	 <li>条件查询商品信息</li>
 *   <li>分页条件查询商品信息</li>
 *   <li>新增商品信息</li>
 *   <li>修改商品信息</li>
 *   <li>修改商品状态</li>
 *   <li>根据商品Id删除商品</li>
 *   <li>根据商品id 加载商品信息</li>
 *   <li>根据商品id 加载该商品相册</li>
 *   <li>修改相册信息</li>
 *   <li>根据相册id删除图片</li>
 * </ul>
 * 
 * @author tangshu
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class GoodsInfoManagerService {

	private static final Logger logger = Logger.getLogger(GoodsInfoManagerService.class);
	
	@Resource private GoodsInfoMapper goodsInfoMapper;
	@Resource private GoodsDescriptionMapper goodsDescriptionMapper;
	@Resource private GoodsInfoAttrDetailMapper goodsInfoAttrDetailMapper;
	@Resource private GoodsImageMapper goodsImageMapper;
	
	/**
	 * 条件查询商品信息
	 * @param goodsInfo
	 * @return
	 */
	public List<GoodsInfo> queryGoodsInfos(GoodsInfo goodsInfo) {
		return goodsInfoMapper.queryBySelective(goodsInfo);
	}
	
	/**
	 * 分页条件查询商品信息
	 * @param query
	 * @param curpage
	 * @param pagesize
	 * @return
	 */
	public Page<GoodsInfo> queryGoodsByPage(GoodsQueryForm query, int curpage,
			int pagesize) {
		//查询分页记录
		List<GoodsInfo> goodsInfoList = goodsInfoMapper.queryGoodsByPage(query, (curpage - 1) * pagesize, pagesize, null, null);
		//总记录行数
		int count = goodsInfoMapper.queryGoodsCount(query);
		//拼装成page对象并返回
		return new Page<GoodsInfo>(goodsInfoList, count, curpage, pagesize);
	}

	/**
	 * 新增商品信息
	 * @param form 商品表单
	 */
	public void insertGood(GoodForm form) {
		logger.info("添加商品:" + form.getGood().getName());
		
		GoodsInfo goodsInfo = form.getGood();
		GoodsDescription goodsDescription = form.getDescription();
		
		//商品图片上传，并保存路径
		ImageInfo image = ImageUtils.upload(form.getImage());
		if (image != null) {
			goodsInfo.setSrcImg(image.getSrcPath());
			goodsInfo.setBigImg(image.getBigPath());
			goodsInfo.setMiddImg(image.getMiddPath());
			goodsInfo.setSmallImg(image.getSmallPath());
		}
		
		//设置添加人和添加时间
		goodsInfo.setAddTime(new Date());
		goodsInfo.setAddUser(ShiroUtils.getCurrentUserId());
		
		//添加商品信息
		goodsInfoMapper.insertSelective(goodsInfo);
		
		//添加商品详情
		goodsDescription.setId(goodsInfo.getId());
		goodsDescriptionMapper.insertSelective(goodsDescription);
		
		//商品相册
		MultipartFile[] images = form.getImages();
		int j = 1;
		for (MultipartFile img : images) {
			//保存文件，如果文件保存失败那么跳到下一个循环
			image = ImageUtils.upload(img);
			if (image == null) continue;
			//保存到数据库
			GoodsImage goodImg = new GoodsImage();
			goodImg.setTitle("图片" + j++);
			goodImg.setSrcImg(image.getSrcPath());
			goodImg.setBigImg(image.getBigPath());
			goodImg.setMiddImg(image.getMiddPath());
			goodImg.setSmallImg(image.getSmallPath());
			goodImg.setGoodId(goodsInfo.getId());
			goodsImageMapper.insertSelective(goodImg);
		}
		
		//保存商品属性
		if (form.getAttrDetailIds() != null && form.getAttrValues() != null) {
			Integer[] attrDetailIds = form.getAttrDetailIds();
			String[] attrValues = form.getAttrValues();
			if (attrDetailIds.length == attrValues.length) {
				for (int i = 0; i < attrDetailIds.length; i++) {
					//保存属性明细数据
					GoodsInfoAttrDetail attrDetail = new GoodsInfoAttrDetail();
					attrDetail.setGoodId(goodsInfo.getId());
					attrDetail.setAttrDetailId(attrDetailIds[i]);
					attrDetail.setAttrValue(attrValues[i]);
					goodsInfoAttrDetailMapper.insertSelective(attrDetail);
				}
			}
		}
	}
	
	/**
	 * 修改商品信息
	 * @param form 商品表单
	 */
	public void updateGood(GoodForm form) {
		logger.info("修改商品信息:" + form.getGood().getId());
		
		GoodsInfo goodsInfo = form.getGood();
		//上传新的商品图片
		ImageInfo image = ImageUtils.upload(form.getImage());
		if (image != null) {
			goodsInfo.setSrcImg(image.getSrcPath());
			goodsInfo.setBigImg(image.getBigPath());
			goodsInfo.setMiddImg(image.getMiddPath());
			goodsInfo.setSmallImg(image.getSmallPath());
		}
		//当前修改用户
		goodsInfo.setUpdateTime(new Date());
		goodsInfo.setUpdateUser(ShiroUtils.getCurrentUserId());
		//修改商品的基本信息
		goodsInfoMapper.updateSelectiveByPrimaryKey(goodsInfo);
		
		//修改商品详情
		goodsDescriptionMapper.updateSelectiveByPrimaryKey(form.getDescription());
		
		//修改相册信息
		Integer[] imageIds = form.getImageIds();		//相册图片id
		MultipartFile[] images = form.getImages();		//上传的图片
		//如果有相册信息
		if (imageIds != null && images != null && imageIds.length == images.length) {
			//如果修改了相册
			for (int i = 0; i < images.length; i++) {
				image = ImageUtils.upload(images[i]);
				if (image == null) continue;
				if (imageIds[i] > 0) {
					//如果是修改图片
					GoodsImage goodImg = goodsImageMapper.selectByPrimaryKey(imageIds[i]);
					if (goodImg != null) {
						//删除原有的图片文件
						ImageUtils.deleteImage(goodImg.getSrcImg());
						ImageUtils.deleteImage(goodImg.getBigImg());
						ImageUtils.deleteImage(goodImg.getMiddImg());
						ImageUtils.deleteImage(goodImg.getSmallImg());
						//修改相册图片
						goodImg.setSrcImg(image.getSrcPath());
						goodImg.setBigImg(image.getBigPath());
						goodImg.setMiddImg(image.getMiddPath());
						goodImg.setSmallImg(image.getSmallPath());
						goodsImageMapper.updateSelectiveByPrimaryKey(goodImg);
					}
				} else {
					//如果是新增图片
					GoodsImage goodImg = new GoodsImage();
					goodImg.setTitle("图片" + (i + 1));
					goodImg.setSrcImg(image.getSrcPath());
					goodImg.setBigImg(image.getBigPath());
					goodImg.setMiddImg(image.getMiddPath());
					goodImg.setSmallImg(image.getSmallPath());
					goodImg.setGoodId(goodsInfo.getId());
					goodsImageMapper.insertSelective(goodImg);
				}
			}
		}
		
		//修改属性信息
		if (form.getGoodAttrDetailIds() != null && 
				form.getAttrDetailIds() != null && 
				form.getAttrValues() != null) {
			Integer[] goodAttrDetailIds = form.getGoodAttrDetailIds();
			Integer[] attrDetailIds = form.getAttrDetailIds();
			String[] attrValues = form.getAttrValues();
			if (goodAttrDetailIds.length == attrDetailIds.length 
					&& attrDetailIds.length == attrValues.length) {
				for (int i = 0; i < goodAttrDetailIds.length; i++) {
					GoodsInfoAttrDetail attrDetail = new GoodsInfoAttrDetail();
					attrDetail.setGoodId(goodsInfo.getId());
					attrDetail.setAttrDetailId(attrDetailIds[i]);
					attrDetail.setAttrValue(attrValues[i]);
					if (goodAttrDetailIds[i] == 0) {
						//保存属性明细数据
						goodsInfoAttrDetailMapper.insertSelective(attrDetail);
					} else {
						//修改明细数据
						goodsInfoAttrDetailMapper.updateSelectiveByPrimaryKey(attrDetail);
					}
				}
				//删除明细（删除条件：good_id为当前商品id，但是却不包含goodAttrDetailIds）
				goodsInfoAttrDetailMapper.deleteByGoodIdAndIds(goodsInfo.getId(), goodAttrDetailIds);
			}
		}
	}
	
	/**
	 * 修改商品状态
	 * @param goodId  商品id
	 * @param status  要修改的状态
	 * @return
	 */
	public int updateGoodsInfoStatus(Integer goodId, GoodStatus status) {
		logger.info("修改商品状态:" + goodId + "|" + status.getText());
		GoodsInfo goodsInfo = new GoodsInfo();
		goodsInfo.setId(goodId);
		goodsInfo.setStatus(status.getCode());
		return goodsInfoMapper.updateSelectiveByPrimaryKey(goodsInfo);
	}
	
	/**
	 * 根据商品Id删除商品
	 * @param goodId 商品id
	 * @return 影响行数
	 */
	public int deleteGoodsInfoById(Integer goodId) {
		logger.info("删除商品:" + goodId);
		return goodsInfoMapper.deleteByPrimaryKey(goodId);
	}
	
	/**
	 * 商品信息
	 * @param good 要修改的商品信息
	 * @return 影响行数
	 */
	public int updateSelectiveByPrimaryKey(GoodsInfo good) {
		return goodsInfoMapper.updateSelectiveByPrimaryKey(good);
	}

	/**
	 * 根据商品id 加载商品信息
	 * @param goodId 商品id
	 * @return
	 */
	public GoodsInfo loadGoodById(Integer goodId) {
		return goodsInfoMapper.selectByPrimaryKey(goodId);
	}
	
	/**
	 * 根据商品id得到商品详情
	 * @param goodId
	 * @return
	 */
	public GoodsDescription loadGoodDescriptionByGoodId(Integer goodId) {
		return goodsDescriptionMapper.selectByPrimaryKey(goodId);
	}

	/**
	 * 根据商品id 加载该商品相册
	 * @param goodId 商品id
	 * @return
	 */
	public List<GoodsImage> getGoodsImagesByGoodId(Integer goodId) {
		GoodsImage entity = new GoodsImage();
		entity.setGoodId(goodId);
		return goodsImageMapper.queryBySelective(entity);
	}
	
	/**
	 * 修改相册信息
	 * @param image
	 */
	public void updateGoodsImage(GoodsImage image) {
		goodsImageMapper.updateSelectiveByPrimaryKey(image);
	}
	
	/**
	 * 根据相册id删除图片
	 * @param imageId
	 */
	public void deleteGoodsImageByImageId(Integer imageId) {
		//查询出相册图片
		GoodsImage image = goodsImageMapper.selectByPrimaryKey(imageId);
		if (image != null) {
			goodsImageMapper.deleteByPrimaryKey(imageId);
			//删除文件
			ImageUtils.deleteImage(image.getSrcImg());
			ImageUtils.deleteImage(image.getBigImg());
			ImageUtils.deleteImage(image.getMiddImg());
			ImageUtils.deleteImage(image.getSmallImg());
		}
	}
}
